package com.starblink.android.basic.sensorsdata.room.dao

import androidx.room.*
import com.starblink.android.basic.sensorsdata.room.config.DatabaseConfig
import com.starblink.android.basic.sensorsdata.room.entity.SKTraceEntity

@Dao
interface SkTraceDao {


    //返回数据库的主键
    @Insert
    suspend fun save(traceData: SKTraceEntity): Long

    //返回数据库的主键集合
    @Insert
    suspend fun saveList(traceData: List<SKTraceEntity>): List<Long>


    @Query("select * from ${DatabaseConfig.spmTableName} limit 1")
    suspend fun queryOne(): SKTraceEntity?



    @Query("select ${DatabaseConfig.spmTableName}.id from ${DatabaseConfig.spmTableName}")
    suspend fun queryItems(): List<Int>?

    @Update
    fun update(traceData: SKTraceEntity)

    @Delete
    fun delete(traceData: SKTraceEntity)

    @Query("select ts from ${DatabaseConfig.spmTableName} order by ts asc limit 1")
    suspend fun getFirstLogTime(): Long

    @Query("select ts from ${DatabaseConfig.spmTableName} order by ts desc limit 1")
    suspend fun getLastLogTime(): Long

    @Query("select * from ${DatabaseConfig.spmTableName} where ts>=:startTime and ts <=:endTime")
    suspend fun getLogByFilter(startTime: Long, endTime: Long): List<SKTraceEntity>


    suspend fun getLogList(startTime: Long = 0, endTime: Long = 0): List<SKTraceEntity> {
        val start = if (startTime == 0L) {
            getFirstLogTime()
        } else {
            startTime
        }
        val end = if (endTime == 0L) {
            getLastLogTime()
        } else {
            endTime
        }
        return getLogByFilter(start, end)
    }
}